package com.zdp.usercenter.controller.user;

import com.zdp.usercenter.auth.CheckLogin;
import com.zdp.usercenter.domain.dto.user.JwtTokenRespDTO;
import com.zdp.usercenter.domain.dto.user.LoginRespDTO;
import com.zdp.usercenter.domain.dto.user.UserLoginDTO;
import com.zdp.usercenter.domain.dto.user.UserRespDTO;
import com.zdp.usercenter.domain.entity.user.User;
import com.zdp.usercenter.service.user.UserService;
import com.zdp.usercenter.util.JwtOperator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sesshomaru
 * @date 2020/9/16 23:54
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    private final JwtOperator jwtOperator;

    @GetMapping("/{id}")
    @CheckLogin
    public User findById(@PathVariable Integer id, HttpServletRequest request){
        log.info("我被请求了...");
        log.info("经过验证登录AOP后从其中request中获取刀的id:{}", request.getAttribute("id"));
        log.info("经过验证登录AOP后从其中request中获取刀的wxNickName:{}", request.getAttribute("wxNickName"));
        log.info("经过验证登录AOP后从其中request中获取刀的role:{}", request.getAttribute("role"));
        return userService.findById(id);
    }

    /**
     * 模拟生成token （假登录）
     * @return
     */
    @GetMapping("gen-token")
    public String genToken(){
        Map<String,Object> userInfo = new HashMap<>(3);
        userInfo.put("id",1);
        userInfo.put("wxNickName","zdp");
        userInfo.put("role","user");
        //userInfo.put("role","admin");
        String token = this.jwtOperator.generateToken(userInfo);
        return token;
    }

    @PostMapping("/login")
    public LoginRespDTO login(@RequestBody UserLoginDTO userLoginDTO){
        // 步骤 微信先登录 --->登录成功 ---->注册 ---> 返回token 换成别的也一样

        // 根据微信提供的code 获取openid和session key信息
        //String code = userLoginDTO.getCode();
        // 这里模拟获取到了一个openid 这里都是调用微信的api获得
        //String openId = userLoginDTO.getOpenId();

        // 看用户是否注册 没有注册就注册一下（插入用户信息）
        // 如果已经注册就 颁发token
        User user = this.userService.login(userLoginDTO, userLoginDTO.getOpenId());

        Map<String,Object> userInfo = new HashMap<>(3);
        userInfo.put("id",user.getId());
        userInfo.put("wxNickName",user.getWxNickname());
        userInfo.put("role",user.getRoles());

        String token = jwtOperator.generateToken(userInfo);
        log.info("用户{}登录成功，生成的token{},有效期到{}",
                userLoginDTO.getWxNickName(),
                token,
                jwtOperator.getExpirationDateFromToken(token));

        // 构建响应
        return LoginRespDTO.builder()
                .userRespDTO(
                        UserRespDTO.builder()
                                .id(user.getId())
                                .avatarUrl(user.getAvatarUrl())
                                .bonus(user.getBonus())
                                .wxNickname(user.getWxNickname())
                                .build()
                )
                .jwtTokenRespDTO(
                        JwtTokenRespDTO.builder()
                                .expirationTime(jwtOperator.getExpirationDateFromToken(token).getTime())
                                .token(token)
                                .build()
                )
                .build();
    }
}
